//
//  DDQuestionChooseCourseViewController.m
//  dingdang
//
//  Created by Chen Jing on 15-7-18.
//  Copyright (c) 2015年 阮 沧晖. All rights reserved.
//

#import "DDQuestionChooseCourseViewController.h"
#import "DDNetWorkAPIClient.h"
#import "DDQuestionChooseCourseTableViewCell.h"

@interface DDQuestionChooseCourseViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>{
    NSMutableArray * array_show;
    ModelQuestionCourse* holdModel;
    BOOL isAddCourse;
}
@property (weak, nonatomic) IBOutlet UIView *contentOfSearchView;
@property (weak, nonatomic) IBOutlet UITableView *table_show;
@property (weak, nonatomic) IBOutlet UITextField *tf_searchOrAdd;

@end

@implementation DDQuestionChooseCourseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self createUI];
    [self createData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)createUI{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBarHidden = YES;

    //自定义TAB BAR UI
    [self addNavigatorTitle:NSLocalizedString(@"科目类别", nil) parent:self.view];
    self.barViewControl.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"top_Background"]];

    [self AddLeftBtnAction:@"" normal:@"top_返回" selected:@"top_返回" action:^{
        [self.navigationController popViewControllerAnimated:YES];
        [self dismissViewControllerAnimated:YES completion:nil];
    }];

    [self.table_show registerNib:[UINib nibWithNibName:NSStringFromClass([DDQuestionChooseCourseTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([DDQuestionChooseCourseTableViewCell class])];

    self.contentOfSearchView.layer.cornerRadius = 5;
    self.contentOfSearchView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.contentOfSearchView.layer.borderWidth = .5;
    self.contentOfSearchView.layer.masksToBounds = YES;

}

-(void)createData{
    array_show = [[NSMutableArray alloc]init];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(checkOptions:) name:UITextFieldTextDidChangeNotification object:nil];
    [self getDataFromServer];
}

-(void)getDataFromServer{
    [self showHUD:@"请稍后..."];
    DDNetWorkAPIClient * client = [[DDNetWorkAPIClient alloc]init];
   
    if (self.info_publishType == DDType_question_questionPublishType_Reward) {
        [client mainDefaultCourseList:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
            if (isSuccess) {
                isAddCourse = NO;
                holdModel = object;
                [array_show removeAllObjects];
                [array_show addObjectsFromArray:holdModel.info_data];
                [self.table_show reloadData];
            }
            [self hideHUD];
        }];
    }else{
        [client mainCoursetList:@{@"type" : [NSNumber numberWithInteger:self.info_publishType]} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
            if (isSuccess) {
                isAddCourse = NO;
                holdModel = object;
                [array_show removeAllObjects];
                [array_show addObjectsFromArray:holdModel.info_data];
                [self.table_show reloadData];
            }
            [self hideHUD];
        }];
    }
}

-(void)checkOptions:(NSNotification *)noti{
    UITextField * tempTf = [noti object];
    NSString * tempString = tempTf.text;
    [array_show removeAllObjects];
    if (tempString.length > 0) {
        for (ModelQuestionCourseElement * element in holdModel.info_data) {
            if ([element.info_title rangeOfString:tempString].length > 0) {
                [array_show addObject:element];
            }
        }
        if (array_show.count < 1) {
            if (self.info_publishType != DDType_question_questionPublishType_Reward) {
                isAddCourse = YES;
            
                ModelQuestionCourseElement * element = [[ModelQuestionCourseElement alloc]init];
                element.info_title = tempString;
                [array_show addObject:element];
            }
            [self.table_show reloadData];
        }else{
            isAddCourse = NO;
            [self.table_show reloadData];
        }
    }else{
        isAddCourse = NO;
        [array_show addObjectsFromArray:holdModel.info_data];
        [self.table_show reloadData];
    }

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return array_show.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DDQuestionChooseCourseTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([DDQuestionChooseCourseTableViewCell class]) forIndexPath:indexPath];
    ModelQuestionCourseElement * element = array_show[indexPath.row];
    cell.label_title.text = element.info_title;
    if (isAddCourse) {
        cell.imageView_plus.hidden = NO;
    }else{
        cell.imageView_plus.hidden = YES;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    ModelQuestionCourseElement * element = array_show[indexPath.row];
    if (isAddCourse) {
        [self addCourse:element];
    }else{
        if (self.delegate && [self.delegate respondsToSelector:@selector(choosedCourse:)]) {
            [self.delegate performSelector:@selector(choosedCourse:) withObject:element];
        }
        [self.navigationController popViewControllerAnimated:YES];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

-(void)addCourse:(ModelQuestionCourseElement *)element{
    [self showHUD:@"请稍后..."];
    DDNetWorkAPIClient * client = [[DDNetWorkAPIClient alloc]init];
    [client mainCoursetAdd:@{@"title" : element.info_title ,@"type" : [NSNumber numberWithInteger:self.info_publishType]} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
        [self hideHUD];
        if (isSuccess == YES && [message isEqualToString:@"成功"]) {
            [self getDataFromServer];
        }
    }];
}


-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
